/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent } from 'react';
import { Icon, Spin, message } from 'antd';
import qs from 'qs';
import './index.less';
import { crypto } from '@/utils/encryption';

class DownloadBar extends PureComponent {
  state = {
    href: '',
    loading: false,
  };

  onLoad = e => {
    let data = { code: 0 };
    try {
      const { innerText } = e.target.contentWindow.document.body;
      data = JSON.parse(innerText);
    } catch (e) {
      data = { code: 0 };
    }
    const { code, msg } = data;
    if (code > 0 && msg) {
      message.error(msg);
    }
    this.timer && clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.setState({
        href: '',
        loading: false,
      });
    }, 0);
  };

  onClick = () => {
    let { href, query, nonceKey } = this.props;
    if (!href) {
      message.error('请配置下载地址');
      return;
    }
    let result = null;
    if (query) {
      result = query();
      if (typeof result === 'string') {
        message.error(result);
        return;
      }
      href = `${href}?${qs.stringify(result)}`;
    }
    const ts = new Date().getTime();
    href = `${href}${href.indexOf('?') >= 0 ? '&' : '?'}ts=${ts}`;
    crypto({
      url: href,
      options: {
        nonceKey,
        data: result,
      },
    }).then(url => {
      this.setState({
        href: url,
        loading: false,
      });
    });
  };

  render() {
    const { loading, href } = this.state;
    const { children, className = '', showIcon, query, ...restProps } = this.props;
    return (
      <span {...restProps} className={`download-wrap ${className}`}>
        <Spin size="small" spinning={loading}>
          <a href="javascript:;" onClick={this.onClick}>
            {showIcon && <Icon style={{ marginRight: 3 }} type="download" theme="outlined" />}
            {children}
          </a>
        </Spin>
        {href && <iframe style={{ display: 'none' }} src={href} onLoad={this.onLoad} />}
      </span>
    );
  }
}

export default DownloadBar;
